<?php

namespace App\Http\Controllers\Api;

use App\Events\SellMember;
use App\Events\SendNoticeToOne;
use App\Events\SendNoticeToSome;
use App\Http\Requests\Api\PaymentRequest;
use App\Http\Requests\Api\PayTypeRequest;
use App\Models\DealLine;
use App\Models\DealLog;
use App\Models\EDealLog;
use App\Models\Member;
use App\Models\Recharge;
use App\Models\Shop;
use App\Models\ShopCrowd;
use App\Models\ShopRole;
use App\Models\User;
use App\Models\Wallet;
use CarBon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

/**
 * @title 充值模块
 * @description 接口说明
 * @header name:accessToken require:1 default: desc:用户token
 */
class RechargeController extends ApiController
{
    /**
     * @title 充值至余额
     * @description 接口说明
     * @author wjx
     * @url /api/recharge/recharge_to_wallet
     * @method POST
     * @param name:total_amount type:int require:1 default:1 other: desc:充值金额(单位元)
     *
     * @return appid:应用ID
     * @return partnerid:商户号
     * @return prepayid:预支付交易会话ID
     * @return timestamp:时间戳
     * @return noncestr:随机字符串
     * @return package:扩展字段
     * @return sign:签名
     */
    public function recharge_to_wallet(Request $request, PaymentRequest $payrequest)
    {
        $user = $request->user;

        $recharge = new Recharge();

        $recharge->user_id = $user->id;
        $recharge->money = $payrequest->total_amount;
        $recharge->type = 1; //充值余额
        $recharge->pay_type = 1; //默认微信
        $recharge->status = 1; //待打款
        $recharge->out_trade_no = set_order_no();

        $res = $recharge->save();

        if ($res) {
            $pay = app('wechat_pay')->app([
                'out_trade_no' => $recharge->out_trade_no,
                'total_fee' => ($payrequest->total_amount) * 100, // 单位是分。
                // 'total_fee' => 1, // 单位是分。
                'body' => '衣E充值余额', // 订单描述
            ]);
            return $this->success(json_decode($pay->getContent()));
        } else {
            return $this->failed('出现异常，请稍后重试');
        }
    }
    /**
     * @title 会员卡类型
     * @description 接口说明:
     * @author wjx
     * @url /api/recharge/getCardDetail
     * @method POST
     *
     * @return card_type:会员卡类型ID
     * @return attr:会员卡规格
     * @return price:会员卡价格
     * @return deposit:会员卡押金
     * @return label:会员卡标签
     * @return desc:会员卡描述
     */
    public function getCardDetail(Request $request)
    {
        $member = Member::whereIn('id', [3, 6])->get();

        if (!$member) {
            return $this->failed('数据错误');
        }
        $member->transform(function ($item) {
            if ($item->time == 3) {
                $attr = '/月';
                $desc = '每次可租两件';
            } else {
                $attr = '/年';
                $desc = '减免两个月会员费';
            }
            return [
                'card_type' => $item->id,
                'attr' => '￥' . $item->price . $attr,
                'price' => $item->price,
                'deposit' => $item->deposit,
                'label' => $item->label,
                'desc' => $desc,
            ];
        });

        return $this->success($member);
    }
    /**
     * @title 充值会员
     * @description 接口说明:
     * @author wjx
     * @url /api/recharge/recharge_to_member
     * @method POST
     * @param name:card_type type:int require:1 default:1 other: desc:会员等级(3月卡6年卡)
     * @param name:pay_type type:int require:1 default:1 other: desc:支付方式(1余额2微信3e格码)
     * @param name:user_id type:int require: default: other: desc:邀请人user_id
     * @param name:shop_id type:int require: default: other: desc:邀请人shop_id
     * @param name:security type:int require: default: other: desc:支付密码
     *
     * @return param:调起微信所需参数
     */
    public function recharge_to_member(Request $request, PayTypeRequest $payRequest)
    {
        $user = $request->user;
        $card_type = (int) $request->card_type;
        $pay_type = (int) $request->pay_type;
        if ($card_type !== 3 && $card_type !== 6) {
            return $this->failed('参数错误');
        }
        $card = Member::where('id', $card_type)->first();

        $level = $card->time;
        $deposit = $card->deposit;
        $total_amount = bcadd($card->price, $deposit, 0);
        $s_user_id = $request->user_id;
        $shop_id = $request->shop_id;
        if ($user->is_member == 1) {
            return $this->failed('你的会员还没到期~');
        }
        if ($s_user_id) {
            $user->fid = $s_user_id;
            $user->shop_id = $shop_id;
            $user->save();
        }
        switch ($pay_type) {
            case '1':
                $res = $this->rechargeMemberByWallet($request, $card);
                if ($res !== true) {
                    return $this->failed($res['message']);
                } else {
                    return $this->message('充值成功');
                }
                break;
            case '2':
                $recharge = new Recharge();
                $recharge->user_id = $user->id;
                $recharge->money = $card->price;
                $recharge->type = 2; //充值会员
                $recharge->deposit = $deposit; //押金
                $recharge->shop_id = $shop_id; //店铺id
                $recharge->pay_type = 2; //默认微信
                $recharge->status = 1; //未成功付款
                $recharge->out_trade_no = set_order_no();

                $user->level = $level;
                DB::beginTransaction();
                try {
                    $user->save();
                    $recharge->save();
                    DB::commit();
                    $pay = app('wechat_pay')->app([
                        'out_trade_no' => $recharge->out_trade_no,
                        'total_fee' => $total_amount * 100, // 单位是分。
                        // 'total_fee' => 1, // 单位是分。
                        'body' => '衣E充值会员', // 订单描述
                    ]);
                    return $this->success(json_decode($pay->getContent()));
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return $this->failed('出现异常，请稍后重试');
                }
                break;
            case '3':
                return $this->failed('该操作不支持使用E格码支付');
            // $res = $this->rechargeMemberByTmc($request, $card);
            // if ($res !== true) {
            //     return $this->failed($res['message']);
            // } else {
            //     return $this->message('充值成功');
            // }
            // break;
            default:
                return $this->failed('支付方式错误');
                break;
        }
    }
    public function rechargeMemberByWallet($request, $card)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        $total_amount = bcadd($card->price, $card->deposit, 0);
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->money < $total_amount) {
            return ['message' => '可用余额不足'];
        }

        $recharge = new Recharge();
        $recharge->user_id = $user->id;
        $recharge->money = $card->price;
        $recharge->type = 2; //充值会员
        $recharge->deposit = $card->deposit; //押金
        $recharge->shop_id = $request->shop_id ? $request->shop_id : 0; //店铺id
        $recharge->pay_type = 1; //默认微信
        $recharge->pay_at = Carbon::now();
        $recharge->status = 2; //成功付款
        $recharge->out_trade_no = set_order_no();

        $user->level = $card->time;
        $user->is_member = 1;
        switch ($card->time) {
            case '3': //月卡
                $user->member_start_time = time();
                $user->member_end_time = strtotime('+1month');
                break;
            case '6': //年卡
                $user->member_start_time = time();
                $user->member_end_time = strtotime('+1year');
                break;
            default:
                break;
        }

        $wallet->deposit = $card->deposit;

        $wallet->money = bcsub($wallet->money, $total_amount);
        DB::beginTransaction();
        try {
            $user->save();
            $wallet->save();
            $recharge->save();
            DealLog::add_log($user->id, 0, $total_amount, 2, '购买会员消耗(余额)');
            event(new SellMember($recharge->id));

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            dd($exception->getMessage());
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }

    }
    public function rechargeMemberByTmc($request, $card)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        $total_amount = bcadd($card->price, $card->deposit, 0);

        $wallet = $user->wallet;
        $today_price = DealLine::orderBy('id', 'desc')->value('price');
        $total_e = bcdiv($total_amount, $today_price, 8);
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->tmc < $total_e) {
            return ['message' => "可用余额不足,需要" . $total_e . "个e格码"];
        }
        $recharge = new Recharge();
        $recharge->user_id = $user->id;
        $recharge->money = $card->price;
        $recharge->tmc = $total_e;
        $recharge->type = 2; //充值会员
        $recharge->deposit = $card->deposit; //押金
        $recharge->shop_id = $request->shop_id ? $request->shop_id : 0; //店铺id
        $recharge->pay_type = 3;
        $recharge->pay_at = Carbon::now();
        $recharge->status = 2; //成功付款
        $recharge->out_trade_no = set_order_no();

        $user->level = $card->time;
        $user->is_member = 1;
        switch ($card->time) {
            case '3': //月卡
                $user->member_start_time = time();
                $user->member_end_time = strtotime('+1month');
                break;
            case '6': //年卡
                $user->member_start_time = time();
                $user->member_end_time = strtotime('+1year');
                break;
            default:
                break;
        }

        $wallet->deposit = $card->deposit;
        $wallet->tmc = bcsub($wallet->tmc, $total_e, 8);
        DB::beginTransaction();
        try {
            $user->save();
            $wallet->save();
            $recharge->save();
            EDealLog::add_log($user->id, 0, $total_e, 2, '购买会员消耗(e格码)', 0);
            event(new SellMember($recharge->id));

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }

    }
    /**
     * @title 会员续费
     * @description 接口说明
     * @author wjx
     * @url /api/recharge/renew_member
     * @method POST
     * @param name:card_type type:int require:1 default:1 other: desc:续费类型(3月卡6年卡)
     * @param name:pay_type type:int require:1 default:1 other: desc:支付方式(1余额2微信3e格码)
     * @param name:security type:string require: default: other: desc:支付密码
     * @param name:user_id type:int require: default: other: desc:邀请人user_id
     * @param name:shop_id type:int require: default: other: desc:邀请人shop_id
     *
     */
    public function renew_member(Request $request, PayTypeRequest $payRequest)
    {
        $user = $request->user;
        $card_type = (int) $request->card_type;
        $pay_type = (int) $request->pay_type;
        $card = Member::where('id', $card_type)->first();
        if (!$card) {
            return $this->failed('参数错误');
        }
        $level = $card->time;
        $total_amount = $card->price;
        $level = (int) $card->time;
        $user_level = (int) $user->member->time;
        if ($user->is_member == 0) {
            return $this->failed('非会员不可续费');
        }
        if ($level !== $user_level) {
            return $this->failed('只能续费同类型会员卡');
        }
        $s_user_id = $request->user_id;
        
        $shop_id = $request->shop_id;
        if ($s_user_id) {
            $user->fid = $s_user_id;
            $user->shop_id = $request->shop_id ? $request->shop_id : 0;
            $user->save();
        }
        
        switch ($pay_type) {
            case '1':
                $res = $this->renewMemberByWallet($request, $card);
                if ($res !== true) {
                    return $this->failed($res['message']);
                } else {
                    return $this->message('续费成功');
                }
                break;
            case '2':
                $recharge = new Recharge();
                $recharge->user_id = $user->id;
                $recharge->money = $total_amount;
                $recharge->type = 3; //续费会员
                $recharge->level = $user_level; //续费会员
                $recharge->shop_id = $request->shop_id ? $request->shop_id : 0; //店铺id
                $recharge->pay_type = 2; //默认微信
                $recharge->status = 1; //未成功付款
                $recharge->out_trade_no = set_order_no();
                DB::beginTransaction();
                try {
                    $recharge->save();
                    DB::commit();
                    $pay = app('wechat_pay')->app([
                        'out_trade_no' => $recharge->out_trade_no,
                        'total_fee' => $total_amount * 100, // 单位是分。
                        // 'total_fee' => 1, // 单位是分。
                        'body' => '衣E会员续费', // 订单描述
                    ]);
                    return $this->success(json_decode($pay->getContent()));
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return $this->failed('出现异常，请稍后重试');
                }
                break;
            case '3':
                $res = $this->renewMemberByTmc($request, $card);
                if ($res !== true) {
                    return $this->failed($res['message']);
                } else {
                    return $this->message('续费成功');
                }
                break;
            default:
                break;
        }
    }

    public function renewMemberByWallet($request, $card)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        $total_amount = $card->price;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->money < $total_amount) {
            return ['message' => '可用余额不足'];
        }
        $recharge = new Recharge();
        $recharge->user_id = $user->id;
        $recharge->money = $total_amount;
        $recharge->type = 3; //续费会员
        $recharge->pay_type = 1; //默认微信
        $recharge->shop_id = $request->shop_id ? $request->shop_id : 0; //店铺id
        $recharge->pay_at = Carbon::now();
        $recharge->status = 2; //成功付款
        $recharge->out_trade_no = set_order_no();
        $user->is_member = 1;
        switch ($user->member->time) {
            case '3': //月卡
                $user->member_end_time = strtotime("+1month", $user->member_end_time);
                break;
            case '6': //年卡
                $user->member_end_time = strtotime('+1year', $user->member_end_time);
                break;
            default:
                break;
        }
        
        $wallet->money = bcsub($wallet->money, $total_amount);
        DB::beginTransaction();
        try {
            $recharge->save();
            $user->save();
            $wallet->save();
            DealLog::add_log($user->id, 0, $total_amount, 2, '续费会员消耗(余额)');
            event(new SellMember($recharge->id));

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            dump($exception->getMessage());
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }
    }

    public function renewMemberByTmc($request, $card)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        $total_amount = $card->price;
        $today_price = DealLine::orderBy('id', 'desc')->value('price');

        $total_e = bcdiv($card->price, $today_price, 8);
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }
        if ($wallet->tmc < $total_e) {
            return ['message' => "可用余额不足,需要" . $total_e . "个e格码"];
        }
        $recharge = new Recharge();
        $recharge->user_id = $user->id;
        $recharge->money = $total_amount;
        $recharge->tmc = $total_e;
        $recharge->type = 3; //续费会员
        $recharge->shop_id = $request->shop_id ? $request->shop_id : 0; //店铺id
        $recharge->pay_type = 3;
        $recharge->pay_at = Carbon::now();
        $recharge->status = 2; //成功付款
        $recharge->out_trade_no = set_order_no();
        $user->is_member = 1;
        switch ($user->member->time) {
            case '3': //月卡
                $user->member_end_time = strtotime("+1month", $user->member_end_time);
                break;
            case '6': //年卡
                $user->member_end_time = strtotime('+1year', $user->member_end_time);
                break;
            default:
                break;
        }
        $wallet->tmc = bcsub($wallet->tmc, $total_e, 8);
        DB::beginTransaction();
        try {
            $recharge->save();
            $user->save();
            $wallet->save();
            EDealLog::add_log($user->id, 0, $total_e, 2, '续费会员消耗(e格码)', 0);
            event(new SellMember($recharge->id));

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['message' => '出现异常，请稍后重试'];
        }
    }

    /**
     * @title 项目认购
     * @description 接口说明
     * @author wjx
     * @url /api/recharge/add_crowd
     * @method POST
     * @param name:type type:int require:1 default: other: desc:认购金额类型(0:500;1:1300;2:5000)
     * @param name:shop_id type:int require:1 default: other: desc:项目id
     * @param name:is_trust type:int require:1 default: other: desc:是否托管1是2否
     * @param name:pay_type type:int require:1 default: other: desc:支付方式(1余额2微信)
     * @param name:security type:string require: default: other: desc:支付密码
     *
     */
    public function add_crowd(Request $request, PayTypeRequest $payRequest)
    {
        $user = $request->user;
        if (!$request->shop_id) {
            return $this->failed('缺少参数');
        }
        if (!in_array($request->is_trust, [1, 2])) {
            return $this->failed('is_trust参数错误');
        }
        $type = $request->type;
        if (!in_array($type, [0, 1, 2])) {
            return $this->failed('type参数错误');
        }
        $pay_type = $request->pay_type;

        $shop = Shop::where('id', $request->shop_id)->first();
        if (!$shop) {
            return $this->failed('店铺不存在');
        }
        if ($shop->crowd_funding_end < time()) {
            return $this->failed('该项目众筹已截止');
        }

        switch ($type) {
            case '0':
                $total_amount = 500;
                $shop_count = Shop::where('id', $request->shop_id)->value('step1');
                $has_count = ShopCrowd::where(['shop_id' => $request->shop_id, 'crowd_type' => 0])->count();
                if ((int) $has_count >= (int) $shop_count) {
                    return $this->failed('该众筹金额份数已满');
                }
                break;
            case '1':
                $total_amount = 1300;
                $shop_count = Shop::where('id', $request->shop_id)->value('step2');
                $has_count = ShopCrowd::where(['shop_id' => $request->shop_id, 'crowd_type' => 1])->count();
                if ((int) $has_count >= (int) $shop_count) {
                    return $this->failed('该众筹金额份数已满');
                }
                break;
            case '2':
                $total_amount = 5000;
                $shop_count = Shop::where('id', $request->shop_id)->value('step3');
                $has_count = ShopCrowd::where(['shop_id' => $request->shop_id, 'crowd_type' => 2])->count();
                if ((int) $has_count >= (int) $shop_count) {
                    return $this->failed('该众筹金额份数已满');
                }
                break;
            default:
                break;
        }

        $crowd_total = ShopCrowd::where('shop_id', $request->shop_id)->sum('money');

        if (($crowd_total + $total_amount) > $shop->shop_price) {
            return $this->failed('众筹金额已超出');
        }

        switch ($pay_type) {
            case '1':
                $res = $this->addCrowdByWallet($request, $total_amount);

                if ($res !== true) {
                    return $this->failed($res['message']);
                } else {
                    return $this->message('认购成功');
                }
                break;
            case '2':
                $recharge = new Recharge();
                $recharge->user_id = $user->id;
                $recharge->money = $total_amount;
                $recharge->type = 4; //项目认购
                $recharge->shop_id = $request->shop_id; //项目ID
                $recharge->is_trust = $request->is_trust; //是否托管
                $recharge->pay_type = 2; //默认微信
                $recharge->status = 1; //未成功付款
                $recharge->out_trade_no = set_order_no();

                $res = $recharge->save();

                if ($res) {
                    $pay = app('wechat_pay')->app([
                        'out_trade_no' => $recharge->out_trade_no,
                        'total_fee' => ($total_amount) * 100, // 单位是分。
                        // 'total_fee' => 1, // 单位是分。
                        'body' => '衣E项目认购', // 订单描述
                    ]);
                    return $this->success(json_decode($pay->getContent()));
                } else {
                    return $this->failed('出现异常，请稍后重试');
                }
                break;
            default:
                return $this->failed('支付方式错误');
                break;
        }
    }

    public function addCrowdByWallet($request, $total_amount)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        if (!Hash::check($request->security, $user->security)) {
            return ['message' => '支付密码错误'];
        }

        if ($wallet->money < $total_amount) {
            return ['message' => "可用余额不足"];
        }

        $crowd = new ShopCrowd();
        $crowd->user_id = $user->id;
        $crowd->shop_id = $request->shop_id;
        $crowd->phone = $user->phone ? $user->phone : '';
        $crowd->crowd_type = $request->type;
        $crowd->money = $total_amount;
        $crowd->pay_type = 1;
        $crowd->is_trust = $request->is_trust;
        $crowd->save();

        $crowd_total = ShopCrowd::where('shop_id', $crowd->shop_id)->sum('money');
        $shop = Shop::where('id', $crowd->shop_id)->first();
        $wallet->money = bcsub($wallet->money, $total_amount, 2);
        DB::beginTransaction();
        try {
            $wallet->save();
            DealLog::add_log($user->id, 0, $total_amount, 2, '认购项目消耗(余额)');
            if ((int) $crowd_total >= (int) $shop->shop_price) {
                $shop->crowd_funding_end = time();
                $shop->status = 3;
                $shop->save();
                $now = Carbon::now()->toDateTimeString();
                //分配会员卡
                $role_dz = ShopRole::where(['shop_id' => $crowd->shop_id, 'role' => 1])->orderBy('hot_spot', 'desc')->first();
                if ($role_dz) {
                    $role_dz->status = 1;
                    $role_dz->save();
                    foreach (range(1, 30) as $index) {
                        $data_dz[] = [
                            'user_id' => $role_dz->user_id,
                            'shop_id' => $role_dz->shop_id,
                            'card_type' => 1,
                            'card_level' => 1,
                            'code' => strtoupper(str_random(20)),
                            'is_used' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    UserCard::insert($data_dz);
                    event(new SendNoticeToOne($role_dz,2,2));
                }

                $role_dy = ShopRole::where(['shop_id' => $crowd->shop_id, 'role' => 2])->orderBy('hot_spot', 'desc')->first();
                if ($role_dy) {
                    $role_dy->status = 1;
                    $role_dy->save();
                    foreach (range(1, 18) as $index) {
                        $data_dy[] = [
                            'user_id' => $role_dy->user_id,
                            'shop_id' => $role_dy->shop_id,
                            'card_type' => 1,
                            'card_level' => 1,
                            'code' => strtoupper(str_random(20)),
                            'is_used' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    UserCard::insert($data_dy);
                    event(new SendNoticeToOne($role_dy, 2, 2));
                }

                $role_md = ShopRole::where(['shop_id' => $crowd->shop_id, 'role' => 3])->orderBy('hot_spot', 'desc')->first();
                if ($role_md) {
                    $role_md->status = 1;
                    $role_md->save();
                    foreach (range(1, 9) as $index) {
                        $data_md[] = [
                            'user_id' => $role_md->user_id,
                            'shop_id' => $role_md->shop_id,
                            'card_type' => 1,
                            'card_level' => 1,
                            'code' => strtoupper(str_random(20)),
                            'is_used' => 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    UserCard::insert($data_md);
                    event(new SendNoticeToOne($role_md, 2, 2));
                }

                //添加会员
                $shop_crowd = ShopCrowd::where('shop_id', $crowd->shop_id)->get();
                event(new SendNoticeToSome($shop_crowd,2,1));
                $shop_crowd->each(function ($item) {
                    if ($item->is_trust == 0) { //成功未托管
                        $user = user::where('id', $item->user_id)->first();
                        switch ($item->crowd_type) {
                            case '0':
                                if ($user->is_member == 1) {
                                    $user->member_end_time = strtotime("+2month", $user->member_end_time);
                                } else {
                                    $user->member_start_time = time();
                                    $user->level = 3;
                                    $user->member_end_time = strtotime("+2month");
                                }
                            case '1':
                                if ($user->is_member == 1) {
                                    $user->member_end_time = strtotime("+6month", $user->member_end_time);
                                } else {
                                    $user->member_start_time = time();
                                    $user->level = 3;
                                    $user->member_end_time = strtotime("+6month");
                                }
                            case '2':
                                if ($user->is_member == 1) {
                                    $user->member_end_time = strtotime("+2year", $user->member_end_time);
                                } else {
                                    $user->member_start_time = time();
                                    $user->level = 3;
                                    $user->member_end_time = strtotime("+2year");
                                }
                                break;
                            default:
                                break;
                        }
                        $user->is_member = 1;
                        $user->save();
                    }
                });
            }
            DB::commit();
            return true;
        } catch (\Exception $exception) {

            DB::rollBack();
            return ['message' => '认购失败'];
        }
    }

}
